package com.briup.njf;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 传统的HTTP的客户端
 */
public class Test5_HttpURLConnection {
    public static void main(String[] args) {
        try {
            // 1. 创建 URL 对象
            URL url = new URL("https://www.jd.com");

            // 2. 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置请求方法（GET）
            connection.setRequestMethod("GET");

            // 4. 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Status code: " + responseCode);

            // 5. 读取响应体
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream())
            );
            StringBuilder response = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
//                response.append(line);
                System.out.println(line);
            }
            reader.close();

            // 6. 输出响应内容
            // System.out.println("Response body: " + response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
